package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone) {
        // 1.验证手机号格式是否正确
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式有误");
        }

        String key = LOGIN_CODE_KEY + phone;
        String code = null;
        // redis存放过code,查看时间是否在1分钟内,防止重刷
        if (stringRedisTemplate.hasKey(key)) {
            code = stringRedisTemplate.opsForValue().get(key);
            System.out.println(code);
            if (!StrUtil.isBlank(code)) {
                long time = Long.parseLong(code.split("_")[1]);
                time = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - time);
                if (time < 120) {
                    return Result.fail("请" + time + "s后再次获取");
                }
            }
        }

        // 2.手机号正确,生成随机验证码,value 带上_时间后缀,用于防止一分钟重刷
        code = RandomUtil.randomString(6) + "_" + System.currentTimeMillis();
        // 3.保存验证码到redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        // 发送验证码,返回结果
        log.info("验证码已发送:{}", code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm) {
        // 1.校验手机号格式
        String phone = loginForm.getPhone();
        String code = loginForm.getCode();
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式有误");
        }
        // 2.获取redis保存的code进行验证
        String codeKey = LOGIN_CODE_KEY + phone;
        if (stringRedisTemplate.hasKey(codeKey)) {
            String codeCache = stringRedisTemplate.opsForValue().get(codeKey);
            codeCache = codeCache.split("_")[0];
            if (!code.equals(codeCache)) {
                return Result.fail("验证码有误");
            }
        } else {
            return Result.fail("请重新获取验证码");
        }
        // 3.判断用户是否注册过,没注册的用户进行注册
        User user = query().eq("phone", phone).one();
        if (user == null) {
            user = createUserWithPhone(phone);
        }
        // 4.保存随机token,将用户对象以hash类型存放到redis,格式LOGIN:token=userMap{k:v;}
        String token = UUID.randomUUID().toString(true);
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        // 存放的hash类型一定是<String,String>,否则会报类型转换错误
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(3), CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldNameConstants, fieldValue) -> fieldValue.toString()));
        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
        //设置用户数据过期时间
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
        // 5.返回token,vue将token设置到cookie和请求头
        return Result.ok(token);
    }

    /**
     * 登出
     * @param token
     * @return
     */
    @Override
    public Result logOut(String token) {
        UserHolder.removeUser();
        stringRedisTemplate.delete(LOGIN_USER_KEY + token);
        return Result.ok("退出成功");
    }

    private User createUserWithPhone(String phone) {
        // 1.创建用户
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        // 2.保存用户
        save(user);
        return user;
    }

}
